package com.zy.serivice.impl;

import com.zy.bean.TMenu;
import com.zy.mapper.TMenuMapper;
import com.zy.service.TMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TMenuServiceImpl implements TMenuService {
    Logger log = LoggerFactory.getLogger(TMenuServiceImpl.class);
    @Autowired
    TMenuMapper tMenuMapper;
    @Override
    public List<TMenu> getList() {

//方式一
 //       List<TMenu> tMenus = new ArrayList<TMenu>();//父菜单and子菜单
//        List<TMenu> allMenus = tMenuMapper.selectByExample(null);
//
//        for (TMenu tMenu : allMenus) {
//            if (tMenu.getPid()==0){//父
//                tMenus.add(tMenu);
//               // stringTMenuHashMap.put(tMenu.getId(),tMenu);
//            }
//        }
//        for (TMenu tMenu : allMenus) {
//            if (tMenu.getPid()!=0){//父
//                for (TMenu menu : tMenus) {
//                    if (menu.getId()==tMenu.getPid()){
//                        menu.getChildren().add(tMenu);
//                    }
//                }
//            }
//        }
        //方式二
        List<TMenu> menuList = new ArrayList<TMenu>(); //只存放父菜单，但是将children属性赋值
        Map<Integer,TMenu> cache = new HashMap<Integer,TMenu>();

        List<TMenu> allMenus = tMenuMapper.selectByExample(null);

        for (TMenu tMenu : allMenus) {
            if(tMenu.getPid() == 0) {
                menuList.add(tMenu);
                cache.put(tMenu.getId(), tMenu);
            }
        }

        for (TMenu tMenu : allMenus) {
            if(tMenu.getPid() != 0) {
                Integer pid = tMenu.getPid();
                TMenu parent = cache.get(pid);
                parent.getChildren().add(tMenu); //根据子菜单pid查找父菜单id,然后根据父菜单children属性进行父子关系组合。
            }
        }

        log.debug("菜单={}",menuList);
        return menuList;
    }

    @Override
    public List<TMenu> getListMenuAll() {
        List<TMenu> tMenus = tMenuMapper.selectByExample(null);
        return tMenus;
    }

    @Override
    public Integer addTmenu(TMenu tMenu) {
        int insert = tMenuMapper.insert(tMenu);
        return insert;
    }

    @Override
    public TMenu getMenuById(Integer id) {
        TMenu tMenu = tMenuMapper.selectByPrimaryKey(id);
        return tMenu;
    }

    @Override
    public Integer updateTree(TMenu tMenu) {
        int i = tMenuMapper.updateByPrimaryKeySelective(tMenu);
        return i;
    }

    @Override
    public Integer delTree(Integer id) {
        int i = tMenuMapper.deleteByPrimaryKey(id);
        return i;
    }
}
